//
//  ZJKOAuthViewController.swift
//  MicroBlog
//
//  Created by VAD on 16/4/19.
//  Copyright © 2016年 朱江坤. All rights reserved.
//

import UIKit

import SVProgressHUD

let WB_APP_KEY = "2127509851"

let WB_APP_SECRET = "59eaec342829199493334a714817d0b3"

let WB_REDIRECT_URI = "http://www.baidu.com"

class ZJKOAuthViewController: UIViewController {
 
    override func loadView() {
        //把webview设置为当前view的根view
        view = webview
        
        
        //让webView加载登录页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APP_KEY)&redirect_uri=\(WB_REDIRECT_URI)"
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        webview.loadRequest(request)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()

    }
    
   private func setupUI(){
    //设置导航标题
    title = "登录"
    //添加导航栏按钮
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
    }
    
    
    // MARK: - 监听方法
    //关闭
    @objc private func close(){
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    //自动填充
    @objc private func autoFill(){
        
        let jsString = "document.getElementById('userId').value='13395654298';document.getElementById('passwd').value='zhu19890814'"
        webview.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
// MARK: -懒加载webview
    private lazy var webview: UIWebView = {
        
        let view = UIWebView()
        
        view.delegate = self
        
        return view
        
    }()

}

// MARK: - 专门用来实现 UIWebViewDelegate 的代理方法的
extension ZJKOAuthViewController:UIWebViewDelegate{
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //取到请求里面的url
        guard let url = request.URL else{
            
            return false
        }
        //判断URL的地址是不是以回调页开头
        if url.absoluteString.hasPrefix(WB_REDIRECT_URI){
            
            if let q = url.query where q.containsString("code="){
                
                let code = q.substringFromIndex("code=".endIndex)
                
                ZJKUserAccountViewModel.sharedViewModel.loadAccessToken(code, finished: { (isSucess) -> () in
                    if isSucess {
                        
                        self.dismissViewControllerAnimated(false, completion: { () -> Void in
                            NSNotificationCenter.defaultCenter().postNotificationName(ZJKChangeRootVCNotification, object: nil)
                        })
                        print("登录成功,关闭当前页面切换根控制器")
                    }else{
                        print("登录失败")
                    }
                })
            }
            return false
        }
        
        return true
    }
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //结束加载
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
